/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.github.xiaoymin.map.spring.configuration;

import cn.hutool.core.collection.CollectionUtil;
import com.github.xiaoymin.map.MapClient;
import com.github.xiaoymin.map.MapClientConfig;
import com.github.xiaoymin.map.ext.AmapClient;
import com.github.xiaoymin.map.ext.BaiduClient;
import com.github.xiaoymin.map.ext.TencentClient;
import com.github.xiaoymin.map.model.AmapKey;
import com.github.xiaoymin.map.spring.properties.MapClientAmapKeyProperty;
import com.github.xiaoymin.map.spring.properties.MapClientAmapProperties;
import com.github.xiaoymin.map.spring.properties.MapClientProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自动注入
 * @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a>
 * 2020/09/23 15:26
 * @since:map-client 1.0
 */
@Configuration
@EnableConfigurationProperties(MapClientProperties.class)
@ConditionalOnProperty(value = "map.client.enable",havingValue = "true",matchIfMissing = true)
public class MapClientConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public MapClient mapClient(MapClientProperties mapClientProperties){
        MapClientConfig mapClientConfig=new MapClientConfig();
        MapClientAmapProperties amapProperties=mapClientProperties.getAmap();
        if (amapProperties!=null){
            if (CollectionUtil.isNotEmpty(amapProperties.getKeys())){
                mapClientConfig.keysAmap(amapProperties.getKeys().toArray(new String[]{}));
            }
            if (CollectionUtil.isNotEmpty(amapProperties.getSigns())){
                List<AmapKey> amapKeys=amapProperties.getSigns().stream().map(MapClientAmapKeyProperty::toAmapKey).collect(Collectors.toList());
                mapClientConfig.keysAmap(amapKeys.toArray(new AmapKey[]{}));
            }
        }
        MapClient mapClient=MapClient.create(mapClientConfig);
        return mapClient;
    }

    @Bean
    @ConditionalOnBean(MapClient.class)
    public AmapClient amapClient(MapClient mapClient){
        return mapClient.amapClient();
    }

    @Bean
    @ConditionalOnBean(MapClient.class)
    public TencentClient tencentClient(MapClient mapClient){
        return mapClient.tencentClient();
    }

    @Bean
    @ConditionalOnBean(MapClient.class)
    public BaiduClient baiduClient(MapClient mapClient){
        return mapClient.baiduClient();
    }
}
